import { defineStore } from "pinia";
import {
  shoppingCart,
  cartItem,
  good,
  shoppingOrder,
} from "@/utils/interface/index";
export const usecartStore = defineStore("cart", {
  state: (): shoppingCart => {
    return {
      carts: [] as cartItem[],
      totalPrice: 0,
    };
  },
  /* 
        类似于组件的computed，用来封装计算属性，有缓存的功能
    */
  getters: {
    priceSum(state): number {
      let sum = 0;
      state.carts.forEach((item: cartItem) => {
        // 商品的价格乘以数量
        sum += item.good.price * item.quantity;
      });
      return sum;
    },
  },
  /* 
        类似于methods,封装业务逻辑，修改state
    */
  actions: {
    // 清空购物车
    clearCart() {
      this.totalPrice = 0;
      this.carts = [];
    },
    // 计算商品数量
    getGoodNum(item: good): number {
      for (let index = 0; index < this.carts.length; index++) {
        if (this.carts[index].good == item) {
          return this.carts[index].quantity;
        }
      }
      return 0;
    },
    // 购物车增加逻辑
    addCartNum(item: good) {
      // 若cartStore.carts里已有，则该商品购物车数量＋1，总金额增加
      for (let index = 0; index < this.carts.length; index++) {
        if (this.carts[index].good == item) {
          this.carts[index].quantity += 1;
          this.totalPrice += item.price;
          // console.log(this);
          return;
        }
      }
      // 若cartStore.carts没有，则加入，总金额增加
      const keycart: cartItem = {
        good: item,
        quantity: 1,
      };
      this.carts.push(keycart);
      this.totalPrice += item.price;
    },
    // 购物车减少逻辑
    minusCartNum(item: good) {
      // 如果购物车里有这个单品，则减除数量，若数量为1时则删除
      for (let index = 0; index < this.carts.length; index++) {
        if (this.carts[index].good == item) {
          if (this.carts[index].quantity == 1) {
            this.carts.splice(index, 1);
          } else {
            this.carts[index].quantity -= 1;
          }
          this.totalPrice -= item.price;
          // console.log(this);
          return;
        }
      }
      // 如没有，则返回一个提示
      console.log("fail");
    },
  },
});

export const useorderStore = defineStore("order", {
  state: (): shoppingOrder => {
    return {
      // 店铺名
      shopName: "",
      // 店铺地址
      shopAddress: "",
      // 订单类型：外带或堂食
      shopType: "",
      // 取餐时间
      pickupTime: "",
      // 订单列表
      myCart: { carts: [], totalPrice: 0 },
      // 是否需要餐具
      tableware: false,
      // 订单备注
      note: "",
    };
  },
  /* 
        类似于组件的computed，用来封装计算属性，有缓存的功能
    */
  getters: {},
  /* 
        类似于methods,封装业务逻辑，修改state
    */
  actions: {
    // 清空订单
    clearOrder() {
      this.shopType = "";
      this.pickupTime = "";
      this.myCart = { carts: [], totalPrice: 0 };
      this.note = "";
    },
  },
});
